<template>
  <div>
    <!-- 头部导航栏 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.go(-1)" />
    <!-- 个人信息编辑栏 -->
    <van-cell title="头像" center is-link @click="imgClickFn">
      <template #default>
        <van-image width="1.333rem" height="1.333rem" round :src="userDetailData.photo" />
        <!-- file 选择框 -->
        <input type="file" ref="iptFile" v-show="false" accept="image/*" @change="onFileChange" />
      </template>
    </van-cell>
    <van-cell title="名称" is-link :value="userDetailData.name" @click="nameClickFn" />
    <van-cell title="性别" is-link :value="userDetailData.gender" @click="genderClickFn" />
    <van-cell title="生日" is-link :value="userDetailData.birthday" @click="birthdayClickFn" />

    <!-- 更改姓名输入框 -->
    <van-dialog v-model="showName" title="更改名称" show-cancel-button :beforeClose="beforeCloseFn"
                :closeOnPopstate="false">
      <van-field v-model="inputUserName" placeholder="请输入用户名" input-align="center" v-fofo />
    </van-dialog>

    <!-- 选择生日日历组件 -->
    <van-popup v-model="showCalendar" position="bottom" :style="{ height: '60%' }">
      <van-datetime-picker v-model="birthday" type="date" title="选择年月日" :min-date="mindate" :max-date="maxdate"
                           @cancel="calendarCancelFn" @confirm="calendarConfirmFn" />
    </van-popup>

    <!-- 选择性别组件 -->
    <van-dialog v-model="showGender" title="标题" show-cancel-button :closeOnPopstate="false" @confirm="genderConfirmFn">
      <van-radio-group class="gender" v-model="gender" direction="horizontal">
        <van-radio name="男">男</van-radio>
        <van-radio name="女">女</van-radio>
      </van-radio-group>
    </van-dialog>

  </div>

</template>

<script>
import { getUserDetailDataAPI, updatePhotoAPI, updateDetailDataAPI } from '@/api'
import Notify from '@/ui/Notify.js'
import { mapMutations } from 'vuex'
export default {
  name: 'UserEdit',
  data() {
    return {
      userDetailData: {}, // 个人详细信息
      showName: false, // 姓名更改框
      inputUserName: '', // 用户名称
      showCalendar: false, // 日历组件
      birthday: '', // 用户生日
      maxdate: new Date(), // 最大日期
      mindate: new Date(1920, 0, 1), // 最小日期
      showGender: false, // 性别组件
      gender: ''
    }
  },
  created() {
    this.getUserDetailDataFn()
  },
  methods: {
    ...mapMutations(['SET_USERPHOTO', 'SET_USERNAME']),
    // 请求详细个人数据
    async getUserDetailDataFn() {
      const { data: res } = await getUserDetailDataAPI()
      this.userDetailData = res.data
      if (this.userDetailData.gender === 1) {
        this.userDetailData.gender = '男'
      } else {
        this.userDetailData.gender = '女'
      }
    },

    // 图片点击事件
    imgClickFn() {
      this.$refs.iptFile.click()
    },
    // 文件选择改变事件
    async onFileChange(e) {
      if (e.target.files.length === 0) return
      const theFd = new FormData() // 创建FormData对象（需求文档表示API请求需要传入FormData对象）
      theFd.append('photo', e.target.files[0]) // 把选中的图片从file格式变为FormData格式
      const { data: res } = await updatePhotoAPI(theFd) // 传入FormData对象
      this.userDetailData.photo = res.data.photo
      // 头像更新成功后，存到vuex中
      this.SET_USERPHOTO(res.data.photo)
    },

    // 更新个人详细信息
    async updateUserDetailDataFn(obj) {
      await updateDetailDataAPI(obj)
    },

    // 名称栏被点击
    nameClickFn() {
      this.showName = true
      this.inputUserName = this.userDetailData.name
    },
    // 更改姓名 确认按钮
    beforeCloseFn(action, done) {
      if (action === 'confirm') {
        // 点击确定
        // 正则判断
        if (/^[A-Za-z0-9\u4e00-\u9fa5]{1,7}$/.test(this.inputUserName)) {
          this.updateUserDetailDataFn({ name: this.inputUserName })
          this.userDetailData.name = this.inputUserName
          // 名字改变后，存到vuex中
          this.SET_USERNAME(this.inputUserName)
          done()
        } else {
          Notify({ type: 'danger', message: '用户名只能是1-7位的数字中英文组合' })
          done(false)
        }
      } else {
        // 点击取消，关闭弹窗
        done()
      }
    },

    // 生日栏被点击
    birthdayClickFn() {
      this.birthday = new Date(this.userDetailData.birthday)
      this.showCalendar = true
    },
    // 更改日历 确认按钮
    calendarConfirmFn(date) {
      this.userDetailData.birthday = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
      this.updateUserDetailDataFn({ birthday: this.userDetailData.birthday })
      this.showCalendar = false
    },
    // 更改日历 取消按钮
    calendarCancelFn() {
      this.showCalendar = false
    },

    // 性别栏被点击
    genderClickFn() {
      this.showGender = true
      this.gender = this.userDetailData.gender
    },
    // 更改性别 确认按钮
    genderConfirmFn() {
      this.userDetailData.gender = this.gender
      if (this.gender === '男') {
        this.gender = 1
      } else {
        this.gender = 0
      }
      this.updateUserDetailDataFn({ gender: this.gender })
    }
  }
}
</script>

<style lang="less" scoped>
.gender {
  display: flex;
  justify-content: space-around;
  padding: 30px;
}
</style>
